package com.smooth.sys.site.biz.pay.ali.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.smooth.common.site.common.enums.SiteCodeEnums;
import com.smooth.common.site.common.excep.SiteException;
import com.smooth.sys.site.biz.pay.ali.config.AlipayConfig;
import com.smooth.sys.site.biz.pay.ali.sign.AliPayMD5;
import com.smooth.sys.site.biz.pay.ali.sign.RSA;
import com.smooth.sys.site.biz.pay.ali.util.AlipayCallBackValidator;
import com.smooth.sys.site.biz.pay.util.SortParamsUtil;
import com.smooth.sys.site.biz.pay.wechat.EnvVarService;

/**
 * 阿里 直接到账 支付 支付接口
 */
@Component
public class GAliPayService {

	private static String _input_charset = "UTF-8";
	private final static Logger log = LoggerFactory.getLogger(GAliPayService.class);

	@Autowired
	AlipayConfig alipayConfig;

	@Autowired
	private AlipayCallBackValidator validator;
	@Value("${alipay.pay.notifyUrl}")
	private String notifyUrl;
	public String getWapPayUrl(String orderNo, double payMoney) {
		String notify_url = alipayConfig.payNotifyUrl;
		String seller_id = alipayConfig.partner;
		String securityCode = alipayConfig.securityCode;
		String subject = "凯顿订单支付";
		String service = "alipay.wap.create.direct.pay.by.user";
		String partner = alipayConfig.partner;

		String payment_type = alipayConfig.paymentType;
		
		if(EnvVarService.isTest()) {
			payMoney = 0.01;
		}
		String total_fee = String.valueOf(payMoney);
		String it_b_pay = alipayConfig.itBPay;

		Map<String, String> hmap = new HashMap<String, String>();
		hmap.put("_input_charset", "utf-8");
		hmap.put("notify_url", notify_url);
		hmap.put("out_trade_no", orderNo);
		hmap.put("payment_type", payment_type);
		hmap.put("total_fee", total_fee);
		hmap.put("seller_email", alipayConfig.sellerEmail);
		hmap.put("subject", subject);
		hmap.put("service", service);
		hmap.put("partner", partner);
		hmap.put("seller_id", seller_id);
		hmap.put("it_b_pay", it_b_pay);
		hmap.put("app_pay", "Y");

		if (StringUtils.isNotEmpty(notifyUrl)) {
			hmap.put("return_url", notifyUrl);
		}
		Set<String> keysetEncode = hmap.keySet();

		hmap = validator.parmFilter(hmap);
		String sortReqStr = SortParamsUtil.createLinkString(hmap);
		String sign = AliPayMD5.sign(sortReqStr, securityCode, AliPayMD5.DEFAULT_ENCODING);

		try {
			for (String key : keysetEncode)
				hmap.put(key, URLEncoder.encode(hmap.get(key), AliPayMD5.DEFAULT_ENCODING));
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			throw new SiteException(SiteCodeEnums.param_error,e.getMessage());
		}

		sortReqStr = SortParamsUtil.createLinkString(hmap);

		String webUrl = new StringBuilder().append(alipayConfig.webPayUrl).append("?").append(sortReqStr).append("&sign=").append(sign).append("&sign_type=MD5").toString();
		log.info(orderNo + " get payurl is [" + webUrl + "]");
		return webUrl;
	}
	
	public String getWebPayUrl(String orderNo, double payMoney,String returnUrl) {
		String notify_url = alipayConfig.payNotifyUrl;
		String seller_id = alipayConfig.partner;
		String securityCode = alipayConfig.securityCode;
		String subject = "凯顿订单支付";
		String service = "create_direct_pay_by_user";
		String partner = alipayConfig.partner;

		String payment_type = alipayConfig.paymentType;
		String total_fee = String.valueOf(payMoney);
		String it_b_pay = alipayConfig.itBPay;

		Map<String, String> hmap = new HashMap<String, String>();
		hmap.put("_input_charset", "utf-8");
		hmap.put("notify_url", notify_url);
		hmap.put("out_trade_no", orderNo);
		hmap.put("payment_type", payment_type);
		hmap.put("total_fee", total_fee);
		hmap.put("seller_email", alipayConfig.sellerEmail);
		hmap.put("subject", subject);
		hmap.put("service", service);
		hmap.put("partner", partner);
		hmap.put("seller_id", seller_id);
		hmap.put("it_b_pay", it_b_pay);
		if(returnUrl!=null){
			hmap.put("return_url",returnUrl);
		}
		Set<String> keysetEncode = hmap.keySet();

		hmap = validator.parmFilter(hmap);
		String sortReqStr = SortParamsUtil.createLinkString(hmap);
		String sign = AliPayMD5.sign(sortReqStr, securityCode, AliPayMD5.DEFAULT_ENCODING);

		try {
			for (String key : keysetEncode)
				hmap.put(key, URLEncoder.encode(hmap.get(key), AliPayMD5.DEFAULT_ENCODING));
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			throw new SiteException(SiteCodeEnums.param_error,e.getMessage());
		}

		sortReqStr = SortParamsUtil.createLinkString(hmap);

		String webUrl = new StringBuilder().append(alipayConfig.webPayUrl).append("?").append(sortReqStr).append("&sign=").append(sign).append("&sign_type=MD5").toString();
		log.info(orderNo + " get payurl is [" + webUrl + "]");
		return webUrl;
	}

	public String getMobilePayUrl(String orderNo, double payMoney, String appid, String appenv) {
		String notify_url = alipayConfig.payNotifyUrl;
		String seller_id = alipayConfig.partner;
		String subject = "凯顿订单支付";
		String service = "mobile.securitypay.pay";
		String partner = alipayConfig.partner;

		String payment_type = alipayConfig.paymentType;
		String total_fee = String.valueOf(payMoney);
		String it_b_pay = alipayConfig.itBPay;

		Map<String, String> hmap = new HashMap<String, String>();

		hmap.put("_input_charset", _input_charset);
		hmap.put("notify_url", notify_url);
		hmap.put("out_trade_no", orderNo);
		hmap.put("payment_type", payment_type);
		hmap.put("total_fee", total_fee);
		hmap.put("seller_email", alipayConfig.sellerEmail);
		hmap.put("subject", subject);
		hmap.put("service", service);
		hmap.put("partner", partner);
		hmap.put("seller_id", seller_id);
		hmap.put("body", subject);
		hmap.put("it_b_pay", it_b_pay);
		hmap.put("appenv", appenv);
		hmap.put("app_id", appid);

		Set<String> keysetEncode = hmap.keySet();

		hmap = validator.parmFilter(hmap);
		// String sign = MD5.getMD5ofStr(sortReqStr+securityCode).toLowerCase();

		// for(String key:keysetEncode){
		// hmap.put(key, URLEncoder.encode(hmap.get(key),"utf-8"));
		// }
		StringBuffer spayurl = new StringBuffer();
		for (String keystr : keysetEncode) {
			spayurl = spayurl.append(keystr + "=\"" + hmap.get(keystr) + "\"&");
		}
		String dspayurl = spayurl.substring(0, spayurl.length() - 1);

		String sign = RSA.sign(dspayurl, alipayConfig.privateKey, "UTF-8");

		try {
			sign = URLEncoder.encode(sign, "utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage());
			throw new SiteException(SiteCodeEnums.param_error,e.getMessage());
		}
		String rurl = dspayurl + "&sign=\"" + sign + "\"&sign_type=\"RSA\"";
		log.info(orderNo + " get payurl is [" + rurl + "]");
		return rurl;
	}
	
}
